package com.andova.egl

import android.opengl.Matrix

class MatrixState {
    companion object {
        private val curMatrix: FloatArray = FloatArray(16)
        fun init() = Matrix.setRotateM(curMatrix, 0, 0f, 1f, 0f, 0f)
        fun rotate(angle: Float, x: Float, y: Float, z: Float) = Matrix.rotateM(curMatrix, 0, angle, x, y, z)
        fun scale(x: Float, y: Float, z: Float) = Matrix.scaleM(curMatrix, 0, x, y, z) // 按 x、y、z 轴进行缩放
        fun translate(x: Float, y: Float, z: Float) = Matrix.translateM(curMatrix, 0, x, y, z) // 沿 x、y、z 轴方向进行平移变换的方法

        /**
         * 总变换矩阵
         */
        private var mvpMatrix = FloatArray(16)
        /**
         * 摄像机位置朝向9参数矩阵
         */
        private var vMatrix = FloatArray(16)
        /**
         * 投影用，4*4矩阵
         */
        private var projMatrix = FloatArray(16)

        fun getFinalMatrix(): FloatArray {
            Matrix.multiplyMM(mvpMatrix, 0, vMatrix, 0, curMatrix, 0) // 摄像机矩阵乘以变换矩阵
            Matrix.multiplyMM(mvpMatrix, 0, projMatrix, 0, mvpMatrix, 0) // 投影矩阵乘以上一步的结果矩阵
            return mvpMatrix
        }

        /**
         * 设置透视投影参数
         */
        fun setProjectFrustum(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float) {
            Matrix.frustumM(projMatrix, 0, left, right, bottom, top, near, far)
        }

        /**
         * 设置摄像机
         */
        fun setCamera(cameraX: Float, cameraY: Float, cameraZ: Float, targetX: Float, targetY: Float, targetZ: Float, upX: Float, upY: Float, upZ: Float) {
            Matrix.setLookAtM(vMatrix, 0, cameraX, cameraY, cameraZ, targetX, targetY, targetZ, upX, upY, upZ)
        }
    }
}